package com.quantdo.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.quantdo.client.Activator;

public class TomcatManageDao {
	private static final String STRICT_HOST_KEY_CHECKING = "StrictHostKeyChecking";
	private static final String NO = "no";
	private static String ip;
	private static String user;
	private static String password;
	static{
		try (InputStream inputStream = Activator.class.getResource("/Config.properties").openStream();){
			Properties properties = new Properties();
			properties.load(inputStream);
			ip = Objects.toString(properties.get("server.ip"));
			user = Objects.toString(properties.get("server.name"));
			password = Objects.toString(properties.get("server.password"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private Session session;

	public ChannelExec createChannelExec() throws JSchException{
		return (ChannelExec)getSession().openChannel("exec");
	}
	public ChannelSftp createChannelSftp() throws JSchException{
		return (ChannelSftp)getSession().openChannel("sftp");
	}
	public static boolean existsSession(String ipAddr, String user, String password) {
		boolean result = false;
		Session session = null;
		try {
			session = createSession(ipAddr, user, password);
			result = session.isConnected();
		} catch (JSchException e) {
			//e.printStackTrace();
		} finally {
			close(session);
		}
		return result;
	}
	private Session getSession() throws JSchException{
		if(null == session || !session.isConnected()){
			session = createSession();
		}
		return session;
	}
	private Session createSession() throws JSchException {
		return createSession(ip, user, password);
	}
	public void close() throws JSchException {
		getSession().disconnect();
	}
	public static void close(Session session) {
		if(null != session) {
			session.disconnect();
		}
	}
	private static Session createSession(String ipAddr, String user, String password) throws JSchException {
		JSch jSch = new JSch();
		Session session = jSch.getSession(user, ipAddr);
		session.setPassword(password);
		Properties sshConfig = new Properties();
		sshConfig.put(STRICT_HOST_KEY_CHECKING, NO);
		session.setConfig(sshConfig);
		session.connect();
		return session;
	}
	
}
